import { sys } from "cc";

export namespace StringTools {

    export const isNullOrEmpty = function (str: string) {
        if (str == null) {
            return true;
        }
        return str.isNullOrEmpty();
    }

    export const toKDotString = function (n: number) {
        let str = '' + n;
        let finalStr = '';
        for (let i = str.length - 1; i >= 0; i--) {
            finalStr = str[i] + finalStr;
            let c = str.length - i;
            if (i != 0) {
                if (c % 3 == 0) {
                    finalStr = ',' + finalStr;
                }
            }
        }
        return finalStr;
    };

    let lastQuery: string = null;
    export const getLastQuery = () => lastQuery;
    export const setLastQuery = (v: string) => lastQuery = v;

    export const parseQueryString = (queryString: string): Record<string, string> => {
        lastQuery = queryString;
        if (queryString.startsWith('?')) queryString = queryString.substring(1);
        const obj = {};
        const pairs = queryString.split('&');
        for (let i = 0; i < pairs.length; i++) {
            const pair = pairs[i].split('=');
            const key = pair[0];
            const value = pair[1];
            if (key && value) {
                obj[key] = value;
            }
        }
        return obj;
    }

    export const getValueInSearch = (key: string): string => {
        if (sys.isBrowser) {
            let search = globalThis.location.search;
            let obj = parseQueryString(search);
            return obj?.[key] ?? obj?.[key.toLowerCase()];
        }
    }
}

declare global {
    interface String {
        isNullOrEmpty(): boolean;
    }
}

String.prototype.isNullOrEmpty = function () {
    return this == null || this.length === 0;
}

globalThis.StringTools = StringTools;